const request = require('./utils/request');
const buildUrl = request.buildUrl || ((url) => url);

App({
  onLaunch() {
    console.log('🚀 小程序启动');
    this.checkInitialLogin();
  },

  doLogin() {
    console.log('🔐 执行登录流程');
    // 这里可以添加登录逻辑，比如跳转到登录页
    wx.reLaunch({
      url: '/pages/login/login'
    });
  },

  checkInitialLogin() {
    const userId = wx.getStorageSync('userId');
    const userRole = wx.getStorageSync('userRole');

    if (!userId) {
      console.log('⛔ 未登录，跳转到登录页');
      wx.reLaunch({
        url: '/pages/login/login'
      });
    } else {
      console.log('✅ 已登录，用户ID:', userId, '角色:', userRole);
      this.globalData.userId = userId;
      this.globalData.userRole = userRole;
      this.globalData.isLoggedIn = true;
      this.redirectToRoleHome(userRole);
    }
  },

  redirectToRoleHome(role) {
    switch (role) {
      case 'order_user':
        wx.reLaunch({ url: '/pages/orderUser/orderUser' });
        break;
      case 'courier':
        wx.reLaunch({ url: '/pages/courier/courier' });
        break;
      default:
        wx.reLaunch({ url: '/pages/index/index' });
    }
  },

  setUserRole(role) {
    wx.setStorageSync('userRole', role);
    this.globalData.userRole = role;
    this.redirectToRoleHome(role);
  },

  switchRole(newRole) {
    this.setUserRole(newRole);
  },

  checkPhoneVerified() {
    return new Promise((resolve) => {
      const userId = this.globalData.userId;
      if (!userId) {
        resolve(false);
        return;
      }

      wx.request({
        url: buildUrl('/api/users/check-phone'),
        method: 'GET',
        data: { userId },
        success: (res) => {
          resolve((res.data && res.data.data && res.data.data.isVerified) || false);
        },
        fail: () => {
          resolve(false);
        }
      });
    });
  },

  globalData: {
    userId: null,
    userRole: null,
    isLoggedIn: false
  }
});